// import common from '@/libs/planCommon'
import industry from './industry'
import shop from './shop'
import category from './category'
import similar from './similar'
import resources from './resources'
import intelligence from './intelligence'
import marketing from './marketing'
import dharma from './dharma'
import visitor from './visitor'

export default {
  name: 'SetUnit',
  data() {
    return {
      day_budget:0,//预算值
      industryList: [],
      shopList: [],
      mine:[{
        "behavior_name": "",
        "behavior_value": ""
      }],
      categoryList:[],
      similarList:[],
      intelligenceList:[],
      checkedPeople:[],
      resourcesList:[],
      resourcesDialog:false,
      multipleSelection:[],
      tongtou:false,//通投
      tongtouPrice:[],
      tongtouList:[{
        crowd_type: "0",
        crowd_name: "通投",
        crowd_value: "all",
        matrix_price: {}
      }],
      marketingList:[],
      dharmaCheck:[],//选中的达摩盘数据
      visitorList:[],
      endError: {//完成计划按钮下的提示
        text: '请将内容填写正确再提交',
        warning: false
      },
      loading: false,
      zywerrorState: false,
      rqerrorState: false
    }
  },
  created(){
    let inputValue = this.$route.query.day_budget/100;//从url里的参数获取的day_budget
    if(inputValue){
      this.day_budget = inputValue;
    }else{
      this.day_budget = JSON.parse(sessionStorage.getItem('campaign')).day_budget;
    }
    // console.log('this.day_budget='+this.day_budget);
  },
  methods: {
    listenIndustry(data){//industryList数据
      this.industryList = data;
      this.endError.warning = false;
      this.rqerrorState = false;
    },
    industryDelete(index) {//删除设置好的行业店铺标签
      this.industryList.splice(index, 1);
    },
    changeprice(item,index,val,i,tmpstr){//出价改变时
      if(tmpstr == 'item_id'){//similarList相似宝贝定向时
        let inputValue = this.$refs[tmpstr+item['id']+item[tmpstr]+'_'+val.adzone_id][0].value;
        // console.log(inputValue)
        item.matrix_price[val.adzone_id]=inputValue;
        if(inputValue<0 ||inputValue==0 || inputValue>this.day_budget){//判断出价的值，必须大于0，小于等于计划日预算
          this.$refs[tmpstr+item['id']+item[tmpstr]+'_'+val.adzone_id][0].nextElementSibling.style.display='block';
        }else{
          this.$refs[tmpstr+item['id']+item[tmpstr]+'_'+val.adzone_id][0].nextElementSibling.style.display='none';
          this.endError.warning = false;
        }
      }else{
        let inputValue = this.$refs[tmpstr+item[tmpstr]+'_'+val.adzone_id][0].value;
        // item.matrix_price[val.adzone_id]=inputValue;
        if(inputValue<0 ||inputValue==0 || inputValue>this.day_budget){//判断出价的值，必须大于0，小于等于计划日预算
          this.$refs[tmpstr+item[tmpstr]+'_'+val.adzone_id][0].nextElementSibling.style.display='block';
        }else{
          this.$refs[tmpstr+item[tmpstr]+'_'+val.adzone_id][0].nextElementSibling.style.display='none';
          this.endError.warning = false;
        }
      }
      // console.log(this.similarList);
    },
    changetongtouprice(val,i){
      let inputValue = this.tongtouPrice[i];
      if(inputValue<0 ||inputValue==0 || inputValue>this.day_budget){//判断出价的值，必须大于0，小于等于计划日预算
        this.$refs['tongtouTip'+i][0].style.display='block';
      }else{
        this.$refs['tongtouTip'+i][0].style.display='none';
        this.endError.warning = false;
      }
      // console.log(this.tongtouPrice)
    },
    listenShop(data){//industryList数据
      this.shopList = data;
      this.endError.warning = false;
      this.rqerrorState = false;
    },
    listenMine(data){//我的店铺名称
      this.mine = data;
      this.endError.warning = false;
      this.rqerrorState = false;
    },
    returnTips(item){//根据返回的不同格式的shopList显示不同格式的数据
      if(item.package_name){
        return item.package_name;
      }else if(item == this.mine[0]){
        return '我的店铺：'+ this.mine[0].behavior_name;
      }else{//店铺细分人群
        let name = '';
        item.time_windows.forEach((val,index)=>{
          if(val.status == 1){
            name = val.time_window_name;
          }
        })
        return item.behavior_name+'-'+name+':'+this.mine[0].behavior_name;
      }
    },
    shopDelete(index) {//删除设置好的行业店铺标签
      this.shopList.splice(index, 1);
    },
    listenCategory(data){//industryList数据
      this.categoryList = data;
      this.endError.warning = false;
      this.rqerrorState = false;
      // console.log(111)
      // console.log(this.categoryList)
    },
    categoryDelete(index) {//删除设置好的行业店铺标签
      this.categoryList.splice(index, 1);
    },
    listensimilar(data){//similarList数据
      this.similarList = data;
      this.$forceUpdate();
      this.endError.warning = false;
      this.rqerrorState = false;
      // console.log(this.similarList);
    },
    similarDelete(index){
      this.similarList.splice(index, 1);
    },
    listenIntelligence(data){//intelligence数据
      this.intelligenceList = data;
      this.endError.warning = false;
      this.rqerrorState = false;
      // console.log(this.intelligenceList);
    },
    intelligenceDelete(index){
      this.intelligenceList.splice(index, 1);
    },
    listenMarketing(data){//marketing数据
      this.marketingList = data;
      this.endError.warning = false;
      this.rqerrorState = false;
      // console.log(this.marketingList);
    },
    returnmarketTips(item){
      let tips = '';
      item.child.forEach((val,index)=>{
        if(val.status == 1){
          tips = tips + val.name+',';
        }
      })
      return item.name+'：'+tips.slice(0,tips.length-1);
    },
    marketingDelete(index){
      this.marketingList.splice(index, 1);
    },
    dharmaDelete(index){
      this.dharmaCheck.splice(index,1)
    },
    listenVisitor(data){//marketing数据
      this.visitorList = data;
      this.endError.warning = false;
      this.rqerrorState = false;
      // console.log(this.visitorList);
    },
    visitorDelete(index){
      this.visitorList.splice(index, 1);
    },
    listenResources(data){//resourcesList数据
      this.resourcesList = data;
      this.endError.warning = false;
      this.zywerrorState = false;
    },
    listenResourcesDialog(data){
      this.resourcesDialog = data;
    },
    resourcesShowModal() {//打开资源位弹框
      this.resourcesDialog = true;
    },
    handleSelectionChange(val){//当选择项发生变化时会触发该事件
      this.multipleSelection = val;
      // console.log(this.multipleSelection);
    },
    deleteResources(index){//移除资源位
      this.resourcesList.splice(index,1);
      // console.log(this.resourcesList);
    },
    deleteAllResources(){//批量移除资源位
      for (let i = 0; i < this.multipleSelection.length; i++) {
        let findIndex = this.resourcesList.findIndex(item => item.adzone_id === this.multipleSelection[i].adzone_id);
        if(findIndex != -1){
          this.resourcesList.splice(findIndex,1);
        }
      }
    },
    returnStr(str){
      return str.join(',');
    },
    toPage(step){//下一步
      this.loading = true;
      var industryObj = {//行业店铺定向最终数据
        "crowd_type": 2048,
        "crowd_name": "CPC店铺定向",
        child:[]
      };
      var _that=this;
      this.industryList.forEach((item,index)=>{//这个是不输入价格的时候点击下一步，input后边的提示会显示出来
        this.resourcesList.forEach((val,i)=>{//出价 resourcesList
          if(!item.matrix_price[val.adzone_id]||item.matrix_price[val.adzone_id]=='' || item.matrix_price[val.adzone_id]<0 || item.matrix_price[val.adzone_id] == 0 || item.matrix_price[val.adzone_id] > this.day_budget){
            _that.$refs['industry_shop_id'+item['industry_shop_id']+'_'+val.adzone_id][0].nextElementSibling.style.display='block';
            this.endError={
              text: '请将内容填写正确再提交',
              warning: true
            }
            this.loading = false;
          }
        });
        industryObj.child.push({"sub_crowd_name":item.industry_shop_name,"sub_crowd_value":item.industry_shop_id,"matrix_price":item['matrix_price']})
      });
      // console.log(industryObj);

      var resourcesArr = [];//资源位最终数据(不能为空)
      this.resourcesList.forEach((item,index)=>{
        resourcesArr.push({"adzone_id":item.adzone_id,"adzone_name":item.adzone_name,"adzone_size_list":item.adzone_size_list})
      });
      // console.log(resourcesArr);


      var shopObj = {//店铺型定向最终数据
        "crowd_type": 2097152,
        "crowd_name": "店铺型定向",
        child:[]
      };
      this.shopList.forEach((item,index)=>{//这个是不输入价格的时候点击下一步，input后边的提示会显示出来
        this.resourcesList.forEach((val,i)=>{//出价 resourcesList
          if(!item.matrix_price[val.adzone_id]||item.matrix_price[val.adzone_id]=='' || item.matrix_price[val.adzone_id]<0 || item.matrix_price[val.adzone_id] == 0 || item.matrix_price[val.adzone_id] > this.day_budget){
            _that.$refs['behavior_value'+item['behavior_value']+'_'+val.adzone_id][0].nextElementSibling.style.display='block';
            this.endError={
              text: '请将内容填写正确再提交',
              warning: true
            }
            this.loading = false;
          }
        });
        if(item.time_windows) {//店铺细分人群
          let findIndex = item.time_windows.findIndex(j => j.status === 1);
          shopObj.child.push({
            "sub_crowd_name": item.time_windows[findIndex].time_window_name,
            "sub_crowd_value": item.time_windows[findIndex].time_window_value,
            "matrix_price": item['matrix_price']
          });
        }else{
          shopObj.child.push({"sub_crowd_name":item.behavior_name,"sub_crowd_value":item.behavior_value,"matrix_price":item['matrix_price']});
        }
      });
      // console.log(shopObj);

      var categoryObj = {//类目型定向最终数据
        "crowd_type": 524288,
        "crowd_name": "类目型定向",
        child:[]
      };
      this.categoryList.forEach((item,index)=>{
        this.resourcesList.forEach((val,i)=>{//出价 resourcesList
          if(!item.matrix_price[val.adzone_id]||item.matrix_price[val.adzone_id]=='' || item.matrix_price[val.adzone_id]<0 || item.matrix_price[val.adzone_id] == 0 || item.matrix_price[val.adzone_id] > this.day_budget){
            _that.$refs['option_value'+item['option_value']+'_'+val.adzone_id][0].nextElementSibling.style.display='block';
            this.endError={
              text: '请将内容填写正确再提交',
              warning: true
            }
            this.loading = false;
          }
        });
        categoryObj.child.push({
          "properties":{
            "_catname": item.cat_name,
            "_catid": item.cat_id
          },
          "sub_crowd_name":item.option_name,
          "sub_crowd_value":item.option_value,
          "matrix_price":item['matrix_price']
        })
      });
      // console.log(categoryObj);

      var similarArr=[];//相似宝贝定向最终数据
      this.similarList.forEach((item,index)=>{//这个是不输入价格的时候点击下一步，input后边的提示会显示出来
        this.resourcesList.forEach((val,i)=>{//出价 resourcesList
          if(!item.matrix_price[val.adzone_id]||item.matrix_price[val.adzone_id]=='' || item.matrix_price[val.adzone_id]<0 || item.matrix_price[val.adzone_id] == 0 || item.matrix_price[val.adzone_id] > this.day_budget){
            _that.$refs['item_id'+item['id']+item['item_id']+'_'+val.adzone_id][0].nextElementSibling.style.display='block';
            this.endError={
              text: '请将内容填写正确再提交',
              warning: true
            }
            this.loading = false;
          }
        });
        similarArr.push({
          "crowd_type": item.id,
          "crowd_name": item.type,
          child:[{
            "sub_crowd_name": item.item_name,
            "sub_crowd_value": item.item_id,
            "matrix_price": item.matrix_price
          }]
        })
      });

      var intelligenceArr = [];//智能定向最终数据
      this.intelligenceList.forEach((item,index)=>{
        this.resourcesList.forEach((val,i)=>{//出价 resourcesList
          if(!item.matrix_price[val.adzone_id]||item.matrix_price[val.adzone_id]=='' || item.matrix_price[val.adzone_id]<0 || item.matrix_price[val.adzone_id] == 0 || item.matrix_price[val.adzone_id] > this.day_budget){
            _that.$refs['id'+item['id']+'_'+val.adzone_id][0].nextElementSibling.style.display='block';
            this.endError={
              text: '请将内容填写正确再提交',
              warning: true
            }
            this.loading = false;
          }
        });
        if(item.scale_desc){
          intelligenceArr.push({
            "crowd_type": item.id,
            "crowd_name": item.type,
            "crowd_value": item.scale_level,
            "matrix_price": item.matrix_price
          })
        }
      })
      // console.log(intelligenceArr);

      // console.log(this.marketingList);
      var marketingObj = {//营销场景定向最终数据
        "crowd_type": 16384,
        "crowd_name": "营销场景定向",
        child:[]
      };
      this.marketingList.forEach((item,index)=>{
        this.resourcesList.forEach((val,i)=>{//出价 resourcesList
          if(!item.matrix_price[val.adzone_id]||item.matrix_price[val.adzone_id]=='' || item.matrix_price[val.adzone_id]<0 || item.matrix_price[val.adzone_id] == 0 || item.matrix_price[val.adzone_id] > this.day_budget){
            _that.$refs['value'+item['value']+'_'+val.adzone_id][0].nextElementSibling.style.display='block';
            this.endError={
              text: '请将内容填写正确再提交',
              warning: true
            }
            this.loading = false;
          }
        });
        marketingObj.child.push({
          "sub_crowd_name":item.name,
          "sub_crowd_value":item.value,
          "matrix_price":item['matrix_price'],
          child:[]
        })
        item.child.forEach((v,j)=>{
          if(v.status == 1){
            marketingObj.child[index].child.push({
              "sub_crowd_name":v.name,
              "sub_crowd_value":v.value
            })
          }
        })
      })
      // console.log(marketingObj);

      // console.log(this.visitorList);
      var visitorObj = {//访客定向最终数据
        "crowd_type": 16,
        "crowd_name": "访客定向",
        child:[]
      };
      if(this.visitorList.length>0){
        visitorObj.crowd_value =  1;
      }
      this.visitorList.forEach((item,index)=>{
        this.resourcesList.forEach((val,i)=>{//出价 resourcesList
          if(!item.matrix_price[val.adzone_id]||item.matrix_price[val.adzone_id]=='' || item.matrix_price[val.adzone_id]<0 || item.matrix_price[val.adzone_id] == 0 || item.matrix_price[val.adzone_id] > this.day_budget){
            _that.$refs['id'+item['id']+'_'+val.adzone_id][0].nextElementSibling.style.display='block';
            this.endError={
              text: '请将内容填写正确再提交',
              warning: true
            }
            this.loading = false;
          }
        });
        visitorObj.child.push({
          "sub_crowd_name":item.name,
          "sub_crowd_value":item.name,
          "matrix_price":item['matrix_price'],
        })
      })
      // console.log(visitorObj);

      var tongtouArr = [];//通投最终数据
      if(this.tongtou){
        this.tongtouList[0].matrix_price={};
        this.tongtouList.forEach((item,index)=>{
          this.resourcesList.forEach((val,i)=>{//出价 resourcesList
            if(!this.tongtouPrice[i]||this.tongtouPrice[i]==''||this.tongtouPrice[i]<0 || this.tongtouPrice[i] == 0 || this.tongtouPrice[i] > this.day_budget){
              this.$refs['tongtouTip'+i][0].style.display='block';
              this.endError={
                text: '请将内容填写正确再提交',
                warning: true
              }
              this.loading = false;
            }else{
              item.matrix_price[val.adzone_id] = this.tongtouPrice[i];
            }
          });
        })
        tongtouArr = this.tongtouList;
      }
      // console.log(tongtouArr)
      var dharmaObj = {//达摩盘最终数据
        "crowd_type": 128,
        "crowd_name": "DMP定向",
        child:[]
      };
      var _that=this;
      this.dharmaCheck.forEach((item,index)=>{//这个是不输入价格的时候点击下一步，input后边的提示会显示出来
        this.resourcesList.forEach((val,i)=>{//出价 resourcesList
          if(!item.matrix_price[val.adzone_id]||item.matrix_price[val.adzone_id]=='' || item.matrix_price[val.adzone_id]<0 || item.matrix_price[val.adzone_id] == 0 || item.matrix_price[val.adzone_id] > this.day_budget){
            _that.$refs['dmp_crowd_id'+item['dmp_crowd_id']+'_'+val.adzone_id][0].nextElementSibling.style.display='block';
            this.endError={
              text: '请将内容填写正确再提交',
              warning: true
            }
            this.loading = false;
          }
        });
        dharmaObj.child.push({"dmp_crowd_name":item.dmp_crowd_name,"dmp_crowd_id":item.dmp_crowd_id,"matrix_price":item['matrix_price']})
      });
      // console.log(dharmaObj);//没有数据，暂时没有测试

      if(resourcesArr.length === 0){//至少选择一个资源位
        this.zywerrorState = true;
        this.endError={
          text: '请至少选择一个资源位',
          warning: true
        }
        this.loading = false;
      }else if(this.industryList.length==0&&this.shopList.length==0&&this.categoryList.length==0&&this.similarList.length==0&&this.intelligenceList.length==0&&this.marketingList.length==0&&this.visitorList.length==0&&this.tongtou==false&&this.dharmaCheck.length==0){//至少有一个人群定向
        this.zywerrorState = false;
        this.rqerrorState = true;
        this.endError = {
          text: '请先添加人群',
          warning: true
        }
        this.loading = false;
      }else if(!this.endError.warning){
        this.zywerrorState = false;
        this.rqerrorState = false;
        // 拼接crowd
        var crowd = [industryObj,shopObj,categoryObj,marketingObj,visitorObj,dharmaObj,...similarArr,...intelligenceArr,...tongtouArr]
        // console.log(crowd);
        var paramsData = {
          "campaign":JSON.parse(sessionStorage.getItem('campaign')),
          "adzone_bid_list": resourcesArr,
          "crowd": crowd
        };
        this.$http( {
          method:'post',
          url:'/zuanzhan/campaign/generate',
          data: paramsData,
          timeout: 120000
        }).then((res) =>  {
          console.log(res);
          if (res.data.code == 200) {
            this.loading = false;
            // console.log("操作成功");
            if(step=='next'){
              this.$store.commit('setPlanStepPool','creative');
              this.$parent.nowStep='creative';
              this.$router.push({path:'/add_plan/setcreative',query:{campaignId:JSON.stringify(res.data.data)}})
            }else{
              this.$message.success('操作成功');
              sessionStorage.removeItem('campaign');
              this.$router.push('/planList');
            }
          }
        }).catch(function (error) {
          console.log(error);
          this.loading = false;
          this.$message.error(error);
        });
      }
      // this.industryList//行业店铺定向
      // this.shopList//店铺型定向最终数据
      // this.categoryList//类目型定向最终数据
      // this.similarList//相似宝贝定向最终数据
      // this.intelligenceList//智能定向最终数据
      // this.marketingList//营销场景定向
      // this.visitorList//访客定向
      // this.tongtou//通投
      // this.dharmaCheck//达摩盘
    },
    goBack(){//返回上一页
      this.$router.go(-1);
    }
  },
  components:{
    industry,
    shop,
    category,
    similar,
    resources,
    intelligence,
    marketing,
    dharma,
    visitor
  }
}
